import React, {useState} from "react";
import { trim } from "lodash";
import Modal from "antd/lib/modal";
import Form from "antd/lib/form";
import Input from "antd/lib/input";
import { wrap as wrapDialog, DialogPropType } from "@/components/DialogWrapper";
import DynamicComponent from "@/components/DynamicComponent";
import {policy} from "@/services/policy";

function CreateItemDialog({dialog }) {
  const [code, setCode] = useState("");
  const [title, setTitle] = useState("");
  const [isValid, setIsValid] = useState(false);
  const [saveInProgress, setSaveInProgress] = useState(false);
  const isCreateEnumsEnabled = policy.isAdmin();

  function handleCodeChange(event) {
    const value = event.target.value.replace(/[^0-9a-zA-z><=!]/g, '');
    setCode(value);
    setIsValid(value !== "" && title !== "");
  }

  function handleTitleChange(event) {
    const value = trim(event.target.value);
    setTitle(value);
    setIsValid(value !== "" && code !== "");
  }

  function handleSubmit() {
    setSaveInProgress(true);
    dialog.close({key: code, value: code, title: code + ' ' + title, label: title});
  }

  return (
    <Modal
      {...dialog.props}
      {...(isCreateEnumsEnabled ? {} : { footer: null })}
      maskClosable = {false}
      title="枚举值"
      okText="保存"
      cancelText="取消"
      okButtonProps={{
        disabled: !isValid || saveInProgress,
        loading: saveInProgress,
        "data-test": "DashboardSaveButton",
      }}
      cancelButtonProps={{
        disabled: saveInProgress,
      }}
      onOk={handleSubmit}
      closable={!saveInProgress}
      wrapProps={{
        "data-test": "CreateDashboardDialog",
      }}>
      <DynamicComponent name="CreateItemDialogExtra" disabled={!isCreateEnumsEnabled}>
      <Form>
        <Form.Item label="编码">
        <Input
          defaultValue={code}
          onChange={handleCodeChange}
          placeholder="编码"
          disabled={saveInProgress}
          autoFocus
        />
        </Form.Item>
        <Form.Item label="名称">
        <Input
          defaultValue={title}
          onChange={handleTitleChange}
          placeholder="名称"
          disabled={saveInProgress}
        />
        </Form.Item>
      </Form>
      </DynamicComponent>
    </Modal>
  );
}

CreateItemDialog.propTypes = {
  dialog: DialogPropType.isRequired,
};

export default wrapDialog(CreateItemDialog);
